﻿namespace UITest.Helpers
{
    using System.Collections.Specialized;
    using System.Configuration;

    using UITest.Report;

    /// <summary>
    ///     The app config helper.
    /// </summary>
    public class AppConfigHelper
    {
        #region Properties

        private ReportListener Report
        {
            get
            {
                return ReportFactory.GetReportListener();
            }
        }

        #endregion

        #region Public Methods and Operators

        /// <summary>
        /// The add update app settings.
        /// </summary>
        /// <param name="key">
        /// The key.
        /// </param>
        /// <param name="value">
        /// The value.
        /// </param>
        public void AddUpdateAppSettings(string key, string value)
        {
            try
            {
                Configuration configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                KeyValueConfigurationCollection settings = configFile.AppSettings.Settings;
                if (settings[key] == null)
                {
                    settings.Add(key, value);
                }
                else
                {
                    settings[key].Value = value;
                }

                configFile.Save(ConfigurationSaveMode.Modified);
                ConfigurationManager.RefreshSection(configFile.AppSettings.SectionInformation.Name);
            }
            catch (ConfigurationErrorsException)
            {
                this.Report.ReportError("Error writing app settings");
            }
        }

        /// <summary>
        /// The read setting.
        /// </summary>
        /// <param name="key">
        /// The key.
        /// </param>
        /// <returns>
        /// The <see cref="string"/>.
        /// </returns>
        public string ReadSetting(string key)
        {
            string result = null;
            try
            {
                NameValueCollection appSettings = ConfigurationManager.AppSettings;
                result = appSettings[key];
            }
            catch (ConfigurationErrorsException)
            {
                this.Report.ReportError("Error reading app settings");
            }

            return result;
        }

        #endregion
    }
}